/**
 * 
 */


const STR_json = 'json';
const STR_text = 'text';
const STR_xml = 'xml';
const STR_object = 'object';
const STR_boolean = 'boolean';
const STR_array = 'array';

const STR_publication = 'publication';
const STR_user = 'user';
const STR_friendship = 'friendship';



//--- 图文部分 开始 ---///////////////

var current_pub = 0;
var numPubs_toget = 5;


//--- 图文部分 结束 ---///////////////




////////////////////////////////////////////
// --- angularJS部分 -- ////////////////////

var mod_myapp = angular.module('myApp',['ngRoute']);


mod_myapp.config(['$routeProvider', function($routeProvider){
	$routeProvider
		.when('/',{
			templateUrl: 'template_main.html',
		})
		.when('/accountmgr',{
			templateUrl:  'template_users.html',
		})
		.when('/personal/:idtovisit',{
			templateUrl: 'template_personal.html',
		})
		.when('/login',{
			templateUrl: 'template_login.html',
			//注意，如果在html中有ng-controller指定controller，此外不要再添加，否则同名controller会导致初始化两个controller； html中指定与此处指定，两者效果相同
			//controller: 'logController',
		})
		.otherwise({
			//redirectTo: '/',
			templateUrl: 'template_invalidUrl.html',
		});
}])
.config(['$locationProvider', function($locationProvider) {
	$locationProvider.html5Mode(false);
	//$locationProvider.hashPrefix('!');
}])
;


mod_myapp
.controller('logController', function($scope, AuthoritySrv, StatusSrv){

	//intializing...
	$scope.account = {
		id: 'id2',
		passwd: '000000'
	};

	$scope.loginResult = {
		succeeded: true,
		msg: "",
	};

	$scope.currentUser = AuthoritySrv.currentUser;
	console.log($scope.currentUser);


	$scope.login = function()
	{
		console.log("login...");

		AuthoritySrv.Login($scope.account.id, $scope.account.passwd, $scope.loginResult);
		console.log("after AuthoritySrv.Login()...");

		console.log($scope.currentUser);
	};

	$scope.logout = function()
	{
		console.log("logout...");

		AuthoritySrv.Logout();
	}
})

.controller('mainController', function($scope, PublicationSrv, StatusSrv, AuthoritySrv){

	//intializing...
	$scope.pub = {
		text: "test text...",
	};

	$scope.submitPub = function()
	{
		if(($scope.pub.text==null || $scope.pub.text == "") && ($scope.pub.img == null))
		{
			alert("文字和图片都为空。请至少输入其中之一。");
			return;
		}

		var promise = PublicationSrv.PostPub($scope.pub.text, $scope.pub.img);
		promise.success(function(data, status, headers, config){

			if(data.status){
				alert("Published succeeded. ID of the new publication: " + data.content.idpub);
				console.log(data);

				//将新发表的图文添加到列表中
				var pubNew = data.content;
				pubNew.usernickname = AuthoritySrv.currentUser.info.nickname;
				$scope.publications.unshift(pubNew);	//注意，unshift()前插，push()后插
				
				$scope.pub = {
					text: "test text...",
					img: null, //图片上传，界面中还是留有文件名，待清理
				};
			}
		}).error(function(data,status,headers, config){
			alert( "data: " + data + " status: " + status);
			StatusSrv.CheckStatus(status);
		});


	};

	$scope.getPubs = function()
	{
		var promise = PublicationSrv.GetAllPubs();


		promise.success(function(data, status, headers, config){
			//alert("Get succeeded");
			console.log(data);
			$scope.publications = data.content;

		}).error(function(data,status,headers, config){
			alert( "data: " + data + " status: " + status);
			StatusSrv.CheckStatus(status);
		});
	};

	$scope.getPubs();
})

.controller('pubsPersonalDisplayController', function($scope, $routeParams, PublicationSrv, UserSrv, StatusSrv, AuthoritySrv){

	$scope.person = {
		isAccessible: false,	//可访问信息的
		info: null,
		publications: null,
	};

	$scope.getPerson = function()
	{
		if($routeParams.idtovisit == AuthoritySrv.currentUser.info.id)
		{
			$scope.person.isAccessible = true;
			$scope.person.info = AuthoritySrv.currentUser.info;

			//验证成功后加载
			$scope.getPubs();
		}
		else
		{
			UserSrv.GetUser_ByID($routeParams.idtovisit)
			.success(function(data, status, headers, config){

				if(data.status)
				{
					$scope.person.isAccessible = true;
					$scope.person.info = data.content;

					console.log($scope.person.info.id);

					//验证成功后加载
					$scope.getPubs();
				}
				else
				{
					console.log(data);
					alert(data.content);
				}
			})
			.error(function(data, status, headers, config){
				console.log(data);
				StatusSrv.CheckStatus(status);
			});			
		}

	};

	$scope.getPubs = function()
	{
		if(!$scope.person.isAccessible || $scope.person.info == null || $scope.person.info.id == null || $scope.person.info.id == "")
		{
			alert("所访问用户非好友，无权查看，或访问无效。");
			return;
		};

		console.log($scope.person.info.id);

		var promise = PublicationSrv.GetPersonalPubs($scope.person.info.id);

		promise.success(function(data, status, headers, config){
			//alert("Get succeeded");
			console.log(data);
			if(data.status){
				$scope.person.publications = data.content;	
			}
			else
			{
				console.log("Get Pubs Failed: " + data.content);
			}

		}).error(function(data,status,headers, config){
			alert( "data: " + data + " status: " + status);
			StatusSrv.CheckStatus(status);
		});
	};


	$scope.getPerson();
})

//by Schelling 2015.06.09 21：24  待统一各请求的返回数据结构，统一在一个表格中显示，并统一有朋友关系及添加删除等操作按钮等



.controller('usersController', function($scope, UserSrv, StatusSrv){

	//方便测试，设置初始值
	$scope.search = {
		//name : "s",
	};

	$scope.DisplayUsersPromise = function(promise)
	{
		promise.success(function(data, status, headers, config){
			console.log("succeeded getAllUsers()...");
			console.log(data);
			$scope.users = data.content;
		}).error(function(data,status,headers, config){
			alert("data:" + data + " status: "+ status);

			StatusSrv.CheckStatus(status);
		});
	}

	$scope.getFriendsOfMy = function(){
		$scope.users = null;
		$scope.DisplayUsersPromise(UserSrv.GetFriends_OfMy());
	};

	$scope.searchUsersLikeNikename = function(){
		$scope.users = null;

		searchName = $scope.search.name;
		if(!searchName) {alert("Please input nickname to search"); return;}

		$scope.DisplayUsersPromise(UserSrv.SearchUsers_LikeNikename(searchName));
	};

	$scope.getAllUsers = function(){
		$scope.users = null;

		$scope.DisplayUsersPromise(UserSrv.GetUsers_All());
	};

	$scope.getFriendRequests = function(){
		$scope.users = null;

		$scope.DisplayUsersPromise(UserSrv.GetFriendRequests());
	};


	$scope.askFriend = function(idToAccept)
	{
		console.log("idToAccept: " + idToAccept);
		if(!idToAccept) { alert("error: idToAccept should not be empty or null."); return;}

		//$scope.DisplayUsersPromise(UserSrv.AskFriend(idToAccept));
		UserSrv.AskFriend(idToAccept)
		.success(function(data,status,headers,config){
			console.log("succeeded askFriend() ");
			console.log(data);

			if(data.status)
			{
				alert("Send friend request succeeded.");	
			}
			else
			{
				alert("Failed.."+ data.content);
			}

		}).error(function(data,status,headers,config){
			alert("data:" + data + " status: "+ status);
			StatusSrv.CheckStatus(status);
		});
	};

	$scope.acceptFriend = function(user)
	{
		idAsk = user.id;

		console.log("idAsk: " + idAsk);
		if(!idAsk) {
			alert("error: idToAccept should not be empty or null."); return;
		}

		UserSrv.AcceptFriend(idAsk)
		.success(function(data,status,headers,config){
			console.log("succeeded acceptFriend() ");
			console.log(data);

			if(data.status)
			{				
				alert("Accept friend request succeeded.");
				
				user.isfriend = "1";
				user.isAskedFriend = "0";
			}
			else{
				alert("Failed.."+ data.content);
			}



		}).error(function(data,status,headers,config){
			alert("data:" + data + " status: "+ status);
			StatusSrv.CheckStatus(status);
		});

	};

	$scope.deleteFriend = function(user)
	{
		idToDelete = user.id;
		console.log("idToDelete: " + idToDelete);
		if(!idToDelete){ alert("error: idToDelete should not be empty or null."); return;}

		UserSrv.DeleteFriend(idToDelete)
		.success(function(data,status,headers,config){
			console.log("succeeded deleteFriend() ");
			console.log(data);

			if(data.status)
			{
				alert("Deleted friend succeeded.");
				
				user.isfriend = "0";
			}	
			else
			{
				alert("Failed..." + data.content);
			}

		}).error(function(data,status,headers,config){
			alert("data:" + data + " status: "+ status);
			StatusSrv.CheckStatus(status);
		});
	}



	$scope.test = function(element)
	{
		element.toggle();
	}
})



.service('AuthoritySrv', ['$http', 'StatusSrv',  function($http, StatusSrv){

	var that = this;	//用于$http请求的结果回调中（如success()）；this无法使用回调函数中，因此使用此参数 ，as a “closure”，见http://stackoverflow.com/questions/14904830/angularjs-service-http-success-function-using-wrong-this-scope

	this.currentUser = {
		islogin: false,
		info: null
	};

	this.CleanCurrentUser = function()
	{
		this.currentUser.islogin = false;
		this.currentUser.info = null;
	}

	this.SetCurrentUserInfo = function(info)
	{
		this.currentUser.islogin = true;
		this.currentUser.info = info;
	}

	this.Login = function(id, passwd, loginResult)
	{
		if(id==null || id=='' || passwd == null || passwd==''){
			alert("id and password should not be empty. ");

			loginResult.succeeded = 0;
			loginResult.msg = "id and password should not be empty. ";

			//return loginResult;
		}

		passwd_sha1 = CryptoJS.SHA1(passwd).toString();
		fd = new FormData();
		fd.append('id', id);
		fd.append('passwd', passwd_sha1);

		$http.post('login.php', fd, {
			headers: {'Content-Type': undefined},
			transformRequest: null,
		})
		.success(function(data, status, headers, config){
			console.log(data);

			if(data.status){
				// that.currentUser = {
				// 	islogin: true, 
				// 	info: data.content,
				// };
				that.SetCurrentUserInfo(data.content);

				StatusSrv.RedirectTo("/");	
				console.log("login succeeded.");		

				loginResult.succeeded = 1;
				loginResult.msg = "login succeeded.";
			}
			else{
				console.log("Failed AuthoritySrv.Login()...");
				//alert("Login Failed: " + data.content);

				loginResult.succeeded = 0;
				loginResult.msg = "Login Failed: "+ data.content;
			}

		})
		.error(function(data,status,headers, config){
			alert( "data: " + data + " status: " + status);

			StatusSrv.CheckStatus(status);
			
			loginResult.succeeded = 0;
			loginResult.msg = "Login Failed: "+ data.content;
		})
		;

	};

	this.Logout = function()
	{
		$http.post('logout.php', {}, {
			headers: {'Content-Type': undefined},
			transformRequest: null,
		})
		.success(function(data, status, headers, config){

			console.log(data);

			if(data.status){
				that.CleanCurrentUser();

				StatusSrv.RedirectTo("login");	
				console.log("login succeeded.");			
			}
			else{				
				alert("Login Failed: " + data);
			}

		})
		.error(function(data,status,headers, config){
			alert( "data: " + data + " status: " + status);
			StatusSrv.CheckStatus(status);
		})
		;
	};

	this.GetCurrentUser = function()
	{
		fd = new FormData();
		fd.append("obj", STR_user);
		fd.append('method', 'get_currentuser');

		$http.post('info.php', fd, {
			headers: {'Content-Type': undefined},
			transformRequest: null,
		})
		.success(function(data, status, headers, config){

			console.log(data);

			if(data.status){
				that.SetCurrentUserInfo(data.content);

				console.log("login succeeded.");			
			}
			else{				
				console.log("Login Failed: " + data);
			}

		})
		.error(function(data,status,headers, config){
			console.log( "data: " + data + " status: " + status);
			StatusSrv.CheckStatus(status);
		})
		;
	};

	//this.GetCurrentUser();
}])

//当前状态的相关服务，包括网页请求返回状态等……
.service('StatusSrv', ['$location', function($location){

	this.CheckStatus = function(status) {

		switch(status)
		{
			case 401:
				//$window.location.href = "login.php";
				this.RedirectToLogin();
				break;

			default: 
				break;
		}
	};

	this.RedirectTo = function(to)
	{
		//$window.location.href = to;
		$location.path(to);
	}

	this.RedirectToLogin = function()
	{
		//$window.location.href = "#/login";
		$location.path('login');
	}

}])

//图文发表浏览相关服务
.service('PublicationSrv', ['$http', '$location', '$window', function($http, $location, $window){

	//Post发表
	this.PostPub = function(text, imgs)
	{
		var fd = new FormData();
		fd.append("obj", STR_publication);
		fd.append("method", 'publish');

		fd.append('text', text);

		var numImgs = imgs == null ? 0 : imgs.length;

		//注意，此处多个文件上传的用法，"FormData() multiple files "
		for(var i=0; i< numImgs; i++)
		{
			fd.append('img[]', imgs[i]);
		}

		return $http.post('info.php', fd, {
			headers: {'Content-Type': undefined},
			transformRequest: null,//angular.identity
		});
	};

	this.GetAllPubs = function()
	{
		return $http({
			method: "GET",
			url: 'info.php',
			params: {obj:STR_publication, method: 'getallpubs' }, 
		});
	};

	this.GetPersonalPubs = function(idtovisit)
	{
		// idtovisit = $location.search().idtovisit;	
		// ll = $window.location;
		// lll= $window.location.href;

		//idtovisit = getParameterByName('idtovisit');

		return $http({
			method: "GET",
			url: 'info.php',
			params: {obj:STR_publication, method: 'getpersonalpubs' , 'idtovisit' : idtovisit }, 
		});
	};

	//获取url参数值，权宜之计，待解决
	//from: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
	function getParameterByName(name) {
	    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
	    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
	        results = regex.exec(location.search);
	    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
	}

}])

//用户及朋友关系相关服务
.service('UserSrv', ['$http', function($http){


	this.GetUser_ByID = function(id)
	{
		return $http.get('info.php?obj=user&method=get_user&id='+id);
	};

	this.GetFriends_OfMy = function()
	{
		return $http.get('info.php?obj=friendship&method=myfriends');
	};

	this.SearchUsers_LikeNikename = function(nicknameLike)
	{
		return $http.get('info.php?obj=user&method=search_nickname_for_friend&nickname='+nicknameLike);
	};

	this.GetUsers_All = function()
	{
		//return $http.get("info.php?obj=user&method=userslist");
		return $http.get(
			"info.php",
			{
				params: {
					obj: "user",
					method: "userslist"	
				}
			});
	};

	this.GetFriendRequests = function()
	{
		return $http.get("info.php?obj=friendship&method=friend_requests");
	};


	this.AskFriend = function(idToAccept)
	{
		fd = new FormData();

		fd.append("obj", "friendship");
		fd.append("method", "ask_friend");
		fd.append("id_toaccept", idToAccept);

		return $http.post(
			"info.php",
			fd,
			{
				headers : {'Content-Type': undefined},
				transformRequest: angular.identity				
			}
		);
	};

	this.AcceptFriend = function(idAsk)
	{
		fd = new FormData();

		fd.append("obj", "friendship");
		fd.append("method", "accept_friend");
		fd.append("id_ask", idAsk);

		return $http.post(
			"info.php",
			fd,
			{
				headers: {'Content-Type': undefined},
				transformRequest: angular.identity
			});
	};


	this.DeleteFriend = function(idToDelete)
	{
		fd = new FormData();
		fd.append("obj", "friendship");
		fd.append("method", "delete_friend");
		fd.append("id_todelete", idToDelete);

		return $http.post(
			"info.php",
			fd,
			{
				headers: {'Content-Type': undefined},
				transformRequest: angular.identity
			});
	};

}])


//自定义指令, 用于处理上传文件
.directive("fileread", [function () {
    return {
    	restrict: 'EA',
        scope: {
            fileread: "="
        },
        //待再看link语法
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                scope.$apply(function () {
                	//上传多个文件或单个
                    //scope.fileread = changeEvent.target.files[0];
                    scope.fileread = changeEvent.target.files;
                });
            });
        }
    }
}])

//注意，此部分涉及动态生成模板的过程, 见http://onehungrymind.com/angularjs-dynamic-templates/ 
//自定义指令<imgs-player>, 用于生成图文列表中的图片html
.directive('imgsPlayer', function() {

	return {
		restrict: 'E',
		scope: {},
		link: function(scope, element, attrs){

			var template = "";
			for(var p=0; p < attrs.numimgs; p++)
	    	{
	    		template += 
	    			"<img src='info.php?obj=publication&method=getimg&idpub=" + attrs.idpub + "&index=" + p + "' width='" +  attrs.width + "'  />";
			}

			//注意，此句重要……  见http://onehungrymind.com/angularjs-dynamic-templates/ 
			element.html(template);//.show();
		},
	};
})

//自定义指令<a-personal>, 用于生成用户的个人主页链接
.directive('aPersonal', function() {

	return {
		restrict: 'E',
		scope: {},
		link: function(scope, element, attrs){

			var template = "<a href='#/personal/"+attrs.userid + "'>" + 
				attrs.usernickname + " (id: " + attrs.userid + ")</a>";

			element.html(template);//.show();
		},
	};
})

;


mod_myapp
.run(function($rootScope, AuthoritySrv)
{
	AuthoritySrv.GetCurrentUser();

})
;



////////////////////////////////////////////